package com.zly.framework.rbac.controller;

import com.zly.framework.rbac.configuration.SysAuthConfiguration;
import com.zly.framework.rbac.exception.SystemException;
import com.zly.framework.rbac.utils.CreateVerifyCode;
import com.zly.framework.rbac.model.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RequestMapping("/sys/common")
@RestController
@Tag(name = "验证码接口")
public class CommonController {
    @Resource
    public SysAuthConfiguration sysAuthConfiguration;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Operation(summary = "返回验证码图片")
    @GetMapping("/captcha/{code}")
    public void getCaptcha(@PathVariable String code, HttpServletResponse response) throws IOException {
        String REDIS_KEY = sysAuthConfiguration.getRedis().getCaptcha() + code;
        String captcha = redisTemplate.opsForValue().get(REDIS_KEY);

        if (!StringUtils.hasText(captcha)) {
            response.setContentType("application/json;charset=UTF-8");
            throw new SystemException("验证码过期");
        }
        CreateVerifyCode createVerifyCode = new CreateVerifyCode(116, 36, 4, 10, captcha);
        response.setContentType("image/png");
        createVerifyCode.write(response.getOutputStream());
    }

    @GetMapping("/captcha/init")
    @Operation(summary = "初始化验证码")
    public Result<Object> initCaptcha() {
        String code = UUID.randomUUID().toString().replace("-", "");
        String REDIS_KEY = sysAuthConfiguration.getRedis().getCaptcha() + code;
        redisTemplate.opsForValue().set(REDIS_KEY, new CreateVerifyCode().randomStr(4), sysAuthConfiguration.getCaptcha().getExpire(), TimeUnit.MINUTES);
        return Result.SUCCESS(code);
    }
}
